<?php
/**
 * https://gitee.com/Mao02
 * http://blog.dazhetu.cn/
 * jay_fun 410136330@qq.com
 * Date: 2018/5/29
 * Time: 10:10
 */

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use think\Db;
use think\facade\Request;
use think\facade\Config;

/**
 * @title 文章管理
 * Class Article
 * @package app\admin\controller
 */
class Article extends BasicAdmin
{

    protected $table = "ContentArticle";

    /**
     * @title 列表页
     * @return array|mixed|\PDOStatement|string|\think\Collection
     */
    public function index()
    {
        $db = Db::name($this->table)
            ->alias('a')
            ->join('__CONTENT_CATEGORY__ c','c.id = a.cid','LEFT')
            ->field('a.*,c.title as ctitle')
            ->where('a.is_deleted','=',0)
            ->order('a.id desc');

        $search = Request::get();
        // 精准查询
        foreach (['state'] as $field){
            if (isset($search[$field]) && $search[$field] !== ''){
                $db->where("a.{$field}",'=', $search[$field]);
            }
        }
        // 模糊查询
        foreach (['title'] as $field){
            if (isset($search[$field]) && $search[$field] !== ''){
                $db->whereLike("a.{$field}", "%{$search[$field]}%");
            }
        }
        // 分类查询
        if (isset($search['cid']) && $search['cid'] !== ''){
//            $db->where("a.{$field}",'=', $search[$field]);
            $ids = Db::name('ContentCategory')
                ->alias('c1')
                ->join('__CONTENT_CATEGORY__ c2','c1.path LIKE CONCAT(c2.path, "%")','LEFT')
                ->where('c2.id','=',$search['cid'])
                ->column("c1.id");
            $db->whereIn('a.cid',$ids);
        }

        return $this->_list($db, true, $search);
    }

    protected function _index_list_before(){
        if (Request::isGet()){
            $list = Db::name('ContentCategory')->select();
            $cates = app('tree')->array2list($list);
            $this->assign('cates',$cates);
        }
    }

    /**
     * @title 添加
     * @return mixed
     */
    public function add()
    {
        return $this->_form('', 'form');
    }

    /**
     * @title 编辑
     * @return mixed
     */
    public function edit()
    {
        return $this->_form('', 'form');
    }

    /**
     * 表单前置
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_before(&$data)
    {
        if (Request::isGet()){
            $list = Db::name('ContentCategory')->select();
            $cates = app('tree')->array2list($list);
            $this->assign('cates',$cates);
        }else{
            $editor = Config::get('app.editor');

            // 内容过滤或者markdown渲染
            if ($editor === 'markdown'){
                $md_content = Request::post('md_content','','strval');
                $parsedown = new \Parsedown();
                $data['content'] = $parsedown->text($md_content);
                $data['md_content'] = $md_content;
            }else{
                $content = Request::post('content','','strval');
                $config = \HTMLPurifier_Config::createDefault();
                $config->set('HTML.SafeIframe',true);
                $config->set('URI.SafeIframeRegexp','%^http://player.youku.com%');
                $config->set('Attr.AllowedFrameTargets',[
                    'height' => true,
                    'width' => true,
                    'src' => true,
                    'frameborder' => true,
                    'allowfullscreen' => true
                ]);
                $purfier = new \HTMLPurifier($config);
                $data['content'] = $purfier->purify($content);
            }
        }
    }

    protected function _form_after($data){
        if (Request::isPost()){
            // 标签提取
            if (!empty($data['id'])){
                Db::name('ContentTagsMap')->where('article_id',$data['id'])->delete();
            }

            $data['keyword'] = str_replace('，',',',$data['keyword']);
            $tags = explode(',',$data['keyword']);
            foreach ($tags as $tag){
                if (empty($tag)){
                    continue;
                }
                $item = Db::name('ContentTags')->where('tag',$tag)->find();
                if (empty($item)){
                    $tag_id = Db::name('ContentTags')->insertGetId(['tag'=>$tag]);
                }else{
                    $tag_id = $item['id'];
                }
                Db::name('ContentTagsMap')->insert([
                    'tag_id'=>$tag_id,
                    'article_id'=>$data['id']
                ]);
            }
        }
    }

    /**
     * 添加前置
     * @param $data
     */
    protected function _add_form_before(&$data){
        if (Request::isPost()){
            $data['create_time'] = Request::time();
            $data['update_time'] = Request::time();
        }
    }

    /**
     * 编辑前置
     * @param $data
     */
    protected function _edit_form_before(&$data){
        if (Request::isPost()){
            $data['update_time'] = Request::time();
        }
    }

    /**
     * @title 删除
     * @throws \think\Exception
     */
    public function del()
    {
        $ids = Request::get('ids');
        $this->_del($ids);
    }

    /**
     * @title 禁用/启用操作
     * @throws \think\Exception
     */
    public function change()
    {
        $id = Request::get('id');
        $state = Request::get('state');
        $this->_change($id, ['state' => $state]);
    }
}